package logic

import (
	"context"
	"encoding/json"
	"library/library/internal/svc"
	"library/library/library"
	"library/models/cache"
	"library/models/mysql"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListActivityLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListActivityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListActivityLogic {
	return &ListActivityLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListActivityLogic) ListActivity(in *library.ListActivityRequest) (*library.ListActivityResponse, error) {
	// todo: add your logic here and delete this line

	page := int(in.Page)
	if page <= 0 {
		page = 1
	}

	pageSize := 5
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var activity []mysql.Activity
	query := mysql.DB.Debug().Offset(offset).Limit(pageSize).Order("created_at desc")

	get := cache.Rdb.Get(l.ctx, "activityList"+strconv.FormatInt(in.Page, 10))
	if get.Val() == "" {
		if in.Title != "" {
			query = query.Where("title like ?", "%"+in.Title+"%")
		}

		query.Find(&activity)

		marshal, _ := json.Marshal(activity)
		cache.Rdb.Set(l.ctx, "activityList"+strconv.FormatInt(in.Page, 10), marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &activity)
	}

	var activityList []*library.ListActivity

	for _, m := range activity {
		list := library.ListActivity{
			Id:      int64(m.ID),
			Title:   m.Title,
			Context: m.Context,
		}
		activityList = append(activityList, &list)
	}

	return &library.ListActivityResponse{List: activityList}, nil
}
